package com.my.api;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.entity.Setting;
import com.my.entity.User;
import com.my.entity.UserMonitor;
import com.my.service.SettingService;
import com.my.service.UserMonitorService;
import com.my.service.UserService;
import com.my.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

@RestController
@RequestMapping("api")
@CrossOrigin
public class LoginApiController {

    @Autowired
    private UserService service;

    @Autowired
    private SettingService sService;

    @Autowired
    private UserMonitorService monitorService;

    @PostMapping("login")
    public Rest login(@RequestBody JSONObject params) {
        User user = service.getById(params.getLong("userId"));
        if(user == null) {
            return Rest.err("该账号不存在！");
        }
        if(SecureUtil.md5(user.getId() + params.getStr("password")).equals(user.getPassword())) {
            return Rest.ok("登录成功！").setData("user", user.setPassword(null).setRollCall(monitorService.getOne(new QueryWrapper<UserMonitor>().eq("user_id", user.getId()).eq("type", 2)) != null)).setData("setting", sService.list().stream().collect(Collectors.toMap(Setting::getSettingKey, Setting::getSettingValue)));
        }
        return Rest.err("学号/工号或密码错误！");
    }

}
